<template>
  <div class="borrow-management">
      <h2>借阅管理</h2>
      <div class="actions">
        <el-button type="success" @click="dialogVisible = true">借阅图书</el-button>
        <el-button
            type="danger"
            :disabled="selectedBorrowRecords.length === 0"
            @click="batchReturnBooks"
        >归还图书</el-button>
        <el-button
            type="warning"
            :disabled="selectedBorrowRecords.length === 0"
            @click="batchRenewBooks"
        >续借图书</el-button>
        <el-button
            type="primary"
            :disabled="selectedBorrowRecords.length === 0"
            @click="batchHandleOverdue"
        >处理逾期归还并封禁</el-button>
      </div>

      <el-table
          :data="borrowedBooks.content"
          style="width: 100%"
          :height="550"
          v-loading="loading"
          row-key="borrowId"
          @selection-change="handleSelectionChange"
          default-sort="{ prop: 'borrowDate', order: 'descending' }"
      >
        <el-table-column type="selection" />
        <el-table-column type="index" label="序号" width="50" />
        <el-table-column prop="cardNumber" label="借阅卡号" />
        <el-table-column prop="bookNumber" label="图书编号" />
        <el-table-column prop="borrowDate" label="借阅日期" sortable/>
        <el-table-column prop="closeDate" label="到期日期" sortable/>
        <el-table-column prop="returnDate" label="归还日期" sortable/>
        <el-table-column prop="borrowing" label="借阅状态" sortable>
          <template #default="scope">
            <el-tag :type="scope.row.borrowing === 1 ? 'danger' : 'success'">
              {{ scope.row.borrowing === 1 ? '借阅中' : '借阅结束' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="processing" label="处理状态" sortable>
          <template #default="scope">
            <el-tag :type="scope.row.processing === 1 ? 'danger' : 'primary'">
              {{ scope.row.processing === 1 ? '逾期待处理' : '已处理' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="violationNote" label="违规记录"/>
      </el-table>
      <!-- 分页组件 -->
      <div class="pagination-actions">
        <el-pagination
            background
            layout="prev, pager, next, sizes, total, jumper"
            :total="borrowedBooks.totalElements"
            :page-size="pagination.size"
            v-model:current-page="pagination.page"
            @update:currentPage="fetchBorrowedBooks"
            @size-change="fetchBorrowedBooks"
        />
      </div>
    <el-dialog
        v-model="dialogVisible"
        title="借阅图书"
        width="30%">
      <el-form :model="borrowForm" label-width="100px">
        <el-form-item label="借阅卡号">
          <el-input
              v-model="borrowForm.cardNumber"
              type="text"
              placeholder="输入你的借阅卡号"
          />
        </el-form-item>
        <el-form-item label="图书编号">
          <el-input
              v-model="borrowForm.bookNumber"
              type="text"
              placeholder="输入借阅的图书编号"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleLend">借阅</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, onMounted} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";
import http from "../utils/axios";
const dialogVisible = ref(false);
const borrowForm = ref({cardNumber: '', bookNumber: '',});
const borrowedBooks = ref({content: [], totalElements: 0});
const pagination = ref({page: 1, size:10});
const selectedBorrowRecords = ref([]);
const loading = ref(false);

const handleLend = async () => {
  try {
    const response = await http.post("/borrow/lend", borrowForm.value);
    if (response.code === 200) {
      ElMessage.success(response.data);
      // 清空表单
      borrowForm.value.cardNumber = '';
      borrowForm.value.bookNumber = '';
      // 关闭对话框
      dialogVisible.value = false;
      // 刷新借阅记录
      await fetchBorrowedBooks();
    } else {
      ElMessage.error(response.data);
    }
  } catch (error) {
    ElMessage.error("借阅失败：" + error.message);
  }
};

const fetchBorrowedBooks = async () => {
  loading.value = true;
  try {
    const response = await http.post("/borrow/all", {
      page: pagination.value.page - 1,
      size: pagination.value.size,
    });
    borrowedBooks.value = response.data || {content: [], totalElements: 0};
  } catch (error) {
    ElMessage.error("获取借阅记录失败：" + error.message);
  } finally {
    loading.value = false;
  }
};

const batchReturnBooks = async () => {
  try {
    const borrowIds = selectedBorrowRecords.value.map((record) => record.borrowId);
    await ElMessageBox.confirm("确认归还选中的图书？", "提示", {
      confirmButtonText: "归还",
      cancelButtonText: "取消",
      type: "warning",
    });
    const response = await Promise.all(
        borrowIds.map((borrowId) => http.put(`/borrow/return/${borrowId}`))
    );
    const successCount = response.filter((res) => res.success).length;
    ElMessage.success(`成功归还 ${successCount} 本图书`);
    await fetchBorrowedBooks();
  } catch (error) {
    ElMessage.error("归还失败：" + error.message);
  }
};

const batchRenewBooks = async () => {
  try {
    const borrowIds = selectedBorrowRecords.value.map((record) => record.borrowId);
    await ElMessageBox.confirm("确认续借选中的图书？", "提示", {
      confirmButtonText: "续借",
      cancelButtonText: "取消",
      type: "warning",
    });
    const responses = await Promise.all(
        borrowIds.map((borrowId) => http.put(`/borrow/renew/${borrowId}`))
    );
    const successCount = responses.filter((res) => res.code === 200 && res.status === true).length;
    if (successCount === borrowIds.length) {
      ElMessage.success(`成功续借 ${successCount} 本图书`);
    } else {
      ElMessage.error(`续借失败：${borrowIds.length - successCount} 本图书续借失败`);
    }
    await fetchBorrowedBooks();
  } catch (error) {
    ElMessage.error("续借失败：" + error.message);
  }
};

const batchHandleOverdue = async () => {
  try {
    const borrowIds = selectedBorrowRecords.value.map((record) => record.borrowId);
    await ElMessageBox.confirm("确认处理选中的逾期记录？", "提示", {
      confirmButtonText: "处理",
      cancelButtonText: "取消",
      type: "warning",
    });
    const responses = await Promise.all(
        borrowIds.map((borrowId) =>
            http.put(`/borrow/overdue/${borrowId}`, null, {
              params: { violationNote: "逾期/禁用账户" }, // 添加到查询参数
            })
        )
    );
    const successCount = responses.filter((res) => res.data.code === 200).length;
    if (successCount > 0) {
      ElMessage.success(`成功处理 ${successCount} 条逾期记录,并禁用对应账户`);
    } else {
      ElMessage.warning("无逾期记录需要处理");
    }
    await fetchBorrowedBooks();
  } catch (error) {
    ElMessage.error("逾期处理失败：" + error.message);
  }
};

const handleSelectionChange = (val) => {
  selectedBorrowRecords.value = val;
};

onMounted(fetchBorrowedBooks);
</script>

<style scoped>
.borrow-management {
  padding: 20px;
}

.actions {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.pagination-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
}
</style>
